<template>
  <div >
    <div class="canvasBox" style="min-height: 500px;" v-loading='loading'>
      <canvas :id="'pdfShow'+(index+100)+''+item+flag" v-for="item in pdfInfo.pdfCount"></canvas>
    </div>
  </div>
</template>

<script>
  import PDFJS from "pdfjs-dist";

  export default{
    data(){
      return {
        pdfInfo:{
          pdfDoc:{},
          pdfCount:0,
          pdfList:[]
        },
        loading:false
      }
    },
    props:{
      pdfDoc:{
        default:null
      },
      pdfUrl:{
        type:String,
        default:''
      },
      index:{
        type:Number,
      },
      flag:''
    },
    methods:{
      handlerPdfDoc(){
        this.$nextTick(()=>{
          this.loading=true
          try{
            if(this.pdfDoc){
              let reader = new FileReader()
              reader.readAsDataURL(this.pdfDoc)
              reader.onload=(res)=>{
              PDFJS.getDocument(res.srcElement.result).promise.then(pdf=>{
                this.pdfInfo.pdfDoc=pdf
                this.pdfInfo.pdfCount=pdf.numPages
                this._renderPage(1)
              })
              }
            }else if(this.pdfUrl!=''){
              PDFJS.getDocument('/api'+this.pdfUrl).promise.then(pdf=>{
                this.pdfInfo.pdfDoc=pdf
                this.pdfInfo.pdfCount=pdf.numPages
                this._renderPage(1)
              })
            }
          }catch(e){
          }
        })
      },
      _renderPage(num){
        this.pdfInfo.pdfDoc.getPage(num).then(page=>{
          let canvas=document.getElementById(`pdfShow${this.index+100}${num}${this.flag}`)
          var vp = page.getViewport({ scale: 2 });
          let ctx = canvas.getContext("2d");
          let viewport = page.getViewport({
            scale: window.innerWidth / vp.width
          });
          canvas.width = viewport.width
          canvas.height = viewport.height
          canvas.style.width = viewport.width + "px"
          canvas.style.height = viewport.height + "px"
          let renderContext = {
            canvasContext: ctx,
            viewport: viewport
          };
          if(canvas){
            page.render(renderContext).then(()=>{
              this.loading=false
              if(this.pdfInfo.pdfCount>num)this._renderPage(num+1)
            })
          }

        })
      },
    },
    mounted(){
      PDFJS.GlobalWorkerOptions.workerSrc = require("pdfjs-dist/build/pdf.worker.min.js");
      this.handlerPdfDoc()
    }
  }
</script>

<style>
</style>
